package com.dmall.chapter05.section03;

import com.dmall.chapter02.section09.Graph;

import java.util.*;

/**
 * 广度优先遍历的单源路径问题
 * @author wx
 * @date 2020-02-27 20:57:48
 */
public class SingleSourcePath {
    private Graph G;
    private int s;
    private boolean[] visited;
    private int[] pre;

    public SingleSourcePath(Graph G, int s) {
        this.G = G;
        this.s = s;
        this.visited = new boolean[G.V()];
        this.pre = new int[G.V()];
        for (int i = 0; i < pre.length; i++) {
            pre[i] = -1;
        }

        bfs(s);
    }

    private void bfs(int s) {
        Queue<Integer> queue = new LinkedList<>();
        queue.add(s);
        visited[s] = true;
        pre[s] = s;
        while (!queue.isEmpty()) {
            int v = queue.remove();

            for (int w : G.adj(v)) {
                if (!visited[w]) {
                    queue.add(w);
                    visited[w] = true;
                    pre[w] = v;
                }
            }
        }
    }

    public boolean isConnectedTo(int t) {
        G.validateVertex(t);
        return visited[t];
    }

    public Iterable<Integer> path(int t) {
        List<Integer> res = new ArrayList<>();
        if (!isConnectedTo(t)) {
            return res;
        }
        int cur = t;
        while (cur != s) {
            res.add(cur);
            cur = pre[cur];
        }
        res.add(s);
        Collections.reverse(res);
        return res;
    }

    public static void main(String[] args) {
        String filename = SingleSourcePath.class.getClassLoader().getResource("g.txt").getPath();
        Graph g = new Graph(filename);

        SingleSourcePath singleSourcePath = new SingleSourcePath(g, 0);
        System.out.println("0 -> 6 : " + singleSourcePath.path(6));

        SingleSourcePath singleSourcePath2 = new SingleSourcePath(g, 0);
        System.out.println("0 -> 5 : " + singleSourcePath.path(5));
    }
}
